export type ToastType = "success" | "error" | "info" | "warning";
export type ToastPosition =
  | "top-left"
  | "top-center"
  | "top-right"
  | "bottom-left"
  | "bottom-center"
  | "bottom-right";

export interface ToastOptions {
  message: string;
  type?: ToastType;
  duration?: number;
  position?: ToastPosition;
}

const namespace = "simple-toast-" + Math.random().toString(36).substr(2, 9);
let toastCount = 0;

const icons = {
  success: `<svg class="w-5 h-5" viewBox="0 0 24 24" fill="#28a745" stroke="black" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
    <path d="M22 11.08V12a10 10 0 1 1-5.93-9.14" />
    <polyline points="22 4 12 14.01 9 11.01" />
  </svg>`,
  error: `<svg class="w-5 h-5" viewBox="0 0 24 24" fill="#dc3545" stroke="black" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
    <circle cx="12" cy="12" r="10" />
    <line x1="15" y1="9" x2="9" y2="15" />
    <line x1="9" y1="9" x2="15" y2="15" />
  </svg>`,
  warning: `<svg class="w-5 h-5" viewBox="0 0 24 24" fill="#ffc107" stroke="black" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
    <path d="M10.29 3.86L1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z" />
    <line x1="12" y1="9" x2="12" y2="13" />
    <line x1="12" y1="17" x2="12.01" y2="17" />
  </svg>`,
  info: `<svg class="w-5 h-5" viewBox="0 0 24 24" fill="#17a2b8" stroke="black" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
    <circle cx="12" cy="12" r="10" />
    <line x1="12" y1="16" x2="12" y2="12" />
    <line x1="12" y1="8" x2="12.01" y2="8" />
  </svg>`,
};

const closeIcon = `<svg class="w-4 h-4" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
  <line x1="18" y1="6" x2="6" y2="18" />
  <line x1="6" y1="6" x2="18" y2="18" />
</svg>`;

const typeClasses: Record<ToastType, string> = {
  success: `${namespace}-success`,
  error: `${namespace}-error`,
  info: `${namespace}-info`,
  warning: `${namespace}-warning`,
};

// 初始化样式
const initializeStyles = () => {
  const style = document.createElement("style");
  style.textContent = `
    .${namespace}-container {
      position: fixed;
      z-index: 99999;
      display: flex;
      flex-direction: column;
      gap: 0.75rem;
      pointer-events: none;
      max-height: 100vh;
      padding: 1rem;
      overflow: hidden;
    }

    .${namespace}-container.top-left {
      top: 0;
      left: 0;
      align-items: flex-start;
    }

    .${namespace}-container.top-center {
      top: 0;
      left: 50%;
      transform: translateX(-50%);
      align-items: center;
    }

    .${namespace}-container.top-right {
      top: 0;
      right: 0;
      align-items: flex-end;
    }

    .${namespace}-container.bottom-left {
      bottom: 0;
      left: 0;
      align-items: flex-start;
      flex-direction: column-reverse;
    }

    .${namespace}-container.bottom-center {
      bottom: 0;
      left: 50%;
      transform: translateX(-50%);
      align-items: center;
      flex-direction: column-reverse;
    }

    .${namespace}-container.bottom-right {
      bottom: 0;
      right: 0;
      align-items: flex-end;
      flex-direction: column-reverse;
    }

    .${namespace} {
      position: relative;
      display: flex;
      align-items: center;
      gap: 0.75rem;
      min-width: 300px;
      max-width: 400px;
      padding: 1rem;
      border-radius: 0.5rem;
      box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
      backdrop-filter: blur(8px);
      pointer-events: auto;
      animation: ${namespace}-slide-in 0.3s ease-out;
    }

    .${namespace}.removing {
      animation: ${namespace}-slide-out 0.3s ease-in forwards;
    }

    @keyframes ${namespace}-slide-in {
      from {
        opacity: 0;
        transform: translateX(100%);
      }
      to {
        opacity: 1;
        transform: translateX(0);
      }
    }

    @keyframes ${namespace}-slide-out {
      from {
        opacity: 1;
        transform: translateX(0);
      }
      to {
        opacity: 0;
        transform: translateX(100%);
      }
    }

    .${namespace}-success {
      background: rgba(0, 200, 0, 0.1);
      border: 1px solid rgba(0, 200, 0, 0.2);
      color: rgb(0, 150, 0);
    }

    .${namespace}-error {
      background: rgba(255, 0, 0, 0.1);
      border: 1px solid rgba(255, 0, 0, 0.2);
      color: rgb(200, 0, 0);
    }

    .${namespace}-info {
      background: rgba(0, 100, 255, 0.1);
      border: 1px solid rgba(0, 100, 255, 0.2);
      color: rgb(0, 100, 200);
    }

    .${namespace}-warning {
      background: rgba(255, 150, 0, 0.1);
      border: 1px solid rgba(255, 150, 0, 0.2);
      color: rgb(200, 100, 0);
    }

    .${namespace}-icon {
      flex-shrink: 0;
      width: 2rem;
      height: 2rem;
      display: flex;
      align-items: center;
      justify-content: center;
      border-radius: 9999px;
      background: currentColor;
      opacity: 0.2;
    }

    .${namespace}-icon svg {
      width: 1.25rem;
      height: 1.25rem;
    }

    .${namespace}-message {
      flex-grow: 1;
      font-size: 0.875rem;
      font-weight: 500;
      word-break: all;
    }

    .${namespace}-close {
      flex-shrink: 0;
      background: none;
      border: none;
      padding: 0;
      cursor: pointer;
      opacity: 0.7;
      transition: opacity 0.2s;
    }

    .${namespace}-close:hover {
      opacity: 1;
    }

    @keyframes ${namespace}-in-right {
      from {
        opacity: 0;
        transform: translateX(100%);
      }
      to {
        opacity: 1;
        transform: translateX(0);
      }
    }

    @keyframes ${namespace}-out-right {
      from {
        opacity: 1;
        transform: translateX(0);
      }
      to {
        opacity: 0;
        transform: translateX(100%);
      }
    }

    @keyframes ${namespace}-in-left {
      from {
        opacity: 0;
        transform: translateX(-100%);
      }
      to {
        opacity: 1;
        transform: translateX(0);
      }
    }

    @keyframes ${namespace}-out-left {
      from {
        opacity: 1;
        transform: translateX(0);
      }
      to {
        opacity: 0;
        transform: translateX(-100%);
      }
    }

    .${namespace}-container.top-right .${namespace},
    .${namespace}-container.bottom-right .${namespace} {
      animation: ${namespace}-in-right 0.3s ease-out;
    }

    .${namespace}-container.top-left .${namespace},
    .${namespace}-container.bottom-left .${namespace} {
      animation: ${namespace}-in-left 0.3s ease-out;
    }

    .${namespace}-container.top-right .${namespace}.removing,
    .${namespace}-container.bottom-right .${namespace}.removing {
      animation: ${namespace}-out-right 0.3s ease-in forwards;
    }

    .${namespace}-container.top-left .${namespace}.removing,
    .${namespace}-container.bottom-left .${namespace}.removing {
      animation: ${namespace}-out-left 0.3s ease-in forwards;
    }
  `;
  document.head.appendChild(style);
  return style;
};

// 创建或获取容器
const getContainer = (position: ToastPosition) => {
  let container = document.getElementById(`${namespace}-${position}`);
  if (!container) {
    container = document.createElement("div");
    container.id = `${namespace}-${position}`;
    container.className = `${namespace}-container ${position}`;
    document.body.appendChild(container);
  }
  return container;
};

const styleElement = initializeStyles();

const removeToast = (toast: HTMLElement) => {
  toast.classList.add("removing");
  setTimeout(() => {
    if (toast.parentNode) {
      const parent = toast.parentElement;
      parent?.removeChild(toast);
      // 检查容器是否为空，如果为空则移除容器
      if (parent?.children.length === 0) {
        parent?.remove();
      }
    }
  }, 300);
};

const createToast = (options: ToastOptions) => {
  const { message, type = "info", position = "top-right" } = options;
  const toast = document.createElement("div");
  const toastId = `${namespace}-toast-${toastCount++}`;
  toast.id = toastId;
  toast.className = `${namespace} ${typeClasses[type]}`;

  toast.innerHTML = `
    <div class="${namespace}-icon">
      ${icons[type]}
    </div>
    <div class="${namespace}-message">${message}</div>
    <button class="${namespace}-close">
      ${closeIcon}
    </button>
  `;

  const container = getContainer(position);
  const closeButton = toast.querySelector(`.${namespace}-close`);
  if (closeButton) {
    closeButton.addEventListener("click", () => removeToast(toast));
  }

  // 根据位置决定插入位置
  if (position.startsWith("bottom")) {
    container.appendChild(toast);
  } else {
    container.insertBefore(toast, container.firstChild);
  }

  setTimeout(() => removeToast(toast), options.duration || 3000);
  return toastId;
};

export const simpleToast = {
  show(message: string, options: Partial<ToastOptions> = {}) {
    return createToast({
      message,
      type: options.type || "info",
      duration: options.duration || 3000,
      position: options.position || "top-center",
    });
  },

  success(message: string, options: Omit<Partial<ToastOptions>, "type"> = {}) {
    return this.show(message, { ...options, type: "success" });
  },

  error(message: string, options: Omit<Partial<ToastOptions>, "type"> = {}) {
    return this.show(message, { ...options, type: "error" });
  },

  info(message: string, options: Omit<Partial<ToastOptions>, "type"> = {}) {
    return this.show(message, { ...options, type: "info" });
  },

  warning(message: string, options: Omit<Partial<ToastOptions>, "type"> = {}) {
    return this.show(message, { ...options, type: "warning" });
  },

  // 移除指定的 toast
  remove(id: string) {
    const toast = document.getElementById(id);
    if (toast) {
      removeToast(toast);
    }
  },

  // 移除所有 toast
  clear() {
    document.querySelectorAll(`[id^="${namespace}-"]`).forEach((el) => {
      el.remove();
    });
  },

  destroy() {
    this.clear();
    if (styleElement && styleElement.parentNode) {
      styleElement.parentNode.removeChild(styleElement);
    }
  },
};

export function useSimpleToast() {
  return simpleToast;
}
